package xl.service;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import xl.model.Document;
import xl.model.EmbeddingData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xl.util.CSVLoader;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

// RAGService.java
@Slf4j
@Service
public class RAGService {
    @Autowired
    private DeepSeekService deepSeekService;

    private final EmbeddingData embeddingData = new EmbeddingData();

    @PostConstruct
    public void init() throws IOException {
        String resourcePath = this.getClass().getClassLoader().getResource("data/business_data.csv").getPath();

        // 初始化时加载CSV数据
        List<Document> documents = new CSVLoader().loadCSV(resourcePath);

        // 生成嵌入并存储
        for (Document doc : documents) {
            List<Double> embedding = deepSeekService.getEmbedding(doc.getContent());
            doc.setEmbedding(embedding);
            embeddingData.addEmbedding(doc);
        }
        log.info("------------------------------------数据加载完成----------------------------------------------------------------");
    }

    public String answerQuestion(String question) throws IOException {
        // 获取问题嵌入
        List<Double> questionEmbedding = deepSeekService.getEmbedding(question);

        // 检索相关文档
        List<Document> relevantDocs = embeddingData.searchSimilar(questionEmbedding, 3);

        // 构建增强后的Prompt
        String context = relevantDocs.stream()
                .map(Document::getContent)
                .collect(Collectors.joining("\n"));

        String prompt = String.format("基于以下业务数据：\n%s\n\n请回答：%s", context, question);

        // 调用大模型生成回答
        return deepSeekService.generateText(prompt);
    }
}

